<template>
  <div>
    <div class="title">基本信息</div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="fromRef"
      class="demo-ruleForm"
    >
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="ruleForm.name"
          style="width: 460px"
          label-width="80px"
          placeholder="请输入优惠券名称"
          maxlength="5"
        ></el-input>
        <span class="remark">优惠券名称不超过5个字</span>
      </el-form-item>
      <el-form-item label="有效时间" prop="useDateValue">
        <el-radio
          v-model="timeRadio"
          label="setTime"
          @change="chooseTimeType"
          :disabled="disType"
          >固定时间</el-radio
        >
        <el-radio
          v-model="timeRadio"
          label="immediate"
          @change="chooseTimeType"
          :disabled="disType"
          >领券立即生效</el-radio
        >
        <div style="margin: 10px 0px 10px 80px">
          <span v-if="timeRadio === 'setTime'">
            <el-date-picker
              v-model="ruleForm.useDateValue.startTime"
              type="date"
              placeholder="开始日期"
              style="width: 220px; margin-left: 15px"
              :picker-options="pickerOptions"
              :disabled="disType"
            ></el-date-picker>
            <span style="margin-left: 10px; color: #ccc">至</span>
            <el-date-picker
              v-model="ruleForm.useDateValue.endTime"
              type="date"
              placeholder="结束日期"
              style="width: 220px; margin-left: 10px"
            ></el-date-picker>
          </span>
          <span v-else>
            领券当日起
            <el-input-number
              :step="1"
              :min="1"
              step-strictly
              :controls="false"
              style="width: 80px; margin: 10px 0px"
              v-model="ruleForm.useDateValue.effectiveDays"
              :disabled="disType"
            ></el-input-number
            >天内可用
          </span>
        </div>
      </el-form-item>
      <el-form-item label="活动规则" prop="actRules">
        <AddcouponComp
          ref="addComp"
          :goodType="goodType"
          :couponContent="couponContent"
          style="padding-left: 95px"
        />
      </el-form-item>
      <el-form-item label="商品选择" prop="actRules">
        <ApointGoods
          style="padding-left: 80px"
          ref="apointComp"
          :actType="actType"
          :content="couponContent"
        />
      </el-form-item>
      <el-form-item label="规则配置" prop="actRules">
        <el-radio-group v-model="recycleActivity" @change="changeModeList">
          <el-radio :label="1">不参与回收返券</el-radio>
          <el-radio :label="2">参与回收返券</el-radio>
        </el-radio-group>
        <div class="couponUpload" v-if="recycleActivity === 2">
          <div class="couponUpload__baseUpload">
            <el-upload
              class="couponUpload__baseUpload--inUpload"
              :auto-upload="false"
              :on-change="uploadProductImg"
              action
              :show-file-list="false"
            >
              <img
                v-if="recycleImg"
                :src="recycleImg"
                style="width: 320px; height: 400px"
              />
              <i class="el-icon-plus" v-else></i>
            </el-upload>
            <div style class="position1">发券字段位置</div>
            <div style class="position2">按钮位置</div>
          </div>

          <div class="couponUploadTip">
            <div
              class="couponUploadTip__tip"
              style="height: 40px; margin-top: 20px"
            >
              <el-upload
                :auto-upload="false"
                :on-change="uploadProductImg"
                action
                :show-file-list="false"
              >
                <p>上传样式</p>
              </el-upload>
              <div>建议尺寸：750 * 1350px</div>
            </div>
            <div class="couponUploadTip__tipTwo">
              设计图片上传时，请将点击按钮尽量对其按钮位置，并在字段位置留空
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <div class="pageButtom">
      <el-button @click="$router.push({ name: 'CouponIndex' })">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import { upLoad } from "@/api/index";
import AddcouponComp from "./AddcouponComp.vue";
import ApointGoods from "../../common/ApointGoods.vue";
import {
  addCoupon,
  couponDetail,
  editCoupon,
} from "@/api/couponActivity/coupon";
import DateUtil from "@/store/modules/date";
Component.registerHooks(["beforeRouteLeave"]);

@Component({
  components: {
    AddcouponComp,
    ApointGoods,
  },
})
export default class AddActivity extends Vue {
  actType = "AddActivity";

  @Ref()
  readonly fromRef: HTMLFormElement;

  @Ref()
  readonly addComp: HTMLFormElement;

  @Ref()
  readonly apointComp: HTMLFormElement;

  validatePass(rule, value, callback) {
    const start = new Date(value.startTime).getTime();
    const end = new Date(new DateUtil("").getYMD(new Date())).getTime();
    if (this.timeRadio === "setTime") {
      if (!value.endTime || !value.startTime) {
        callback(new Error("请输入活动时间"));
      } else {
        if (value.startTime.getTime() > value.endTime.getTime()) {
          callback(new Error("结束时间不能小于开始时间"));
        }
        if (start < end) {
          if (this.couponContent.status != 1) {
            callback(new Error("开始时间不能小于当前时间"));
          }
        }
      }
    } else {
      const regs = /^[+]{0,1}(\d+)$/;
      if (!regs.test(value.effectiveDays)) {
        callback(new Error("有效期请输入整数"));
      } else if (value.effectiveDays <= 0) {
        callback(new Error("有效期不能小于1"));
      } else {
        callback();
      }
    }
  }

  rulevalidate() {
    console.log("test");
  }

  pickerOptions = {
    disabledDate(time) {
      const now = new Date(new Date().toLocaleDateString()).getTime();
      return time.getTime() < now;
    },
  };

  /** 优惠券使用时间 */
  timeRadio = "setTime";

  /** 禁用状态 */
  disType = false;

  /** 商品选择类型 */
  goodType = 0;

  /** 是否参与回收返券 */
  recycleActivity = 1;

  /** 返券图片 */
  recycleImg = "https://oss-tencent.bgniao.cn/api/recycle_discount_coupon.png";

  ruleForm = {
    name: "",
    useDateValue: {
      startTime: "" as any,
      endTime: "" as any,
      effectiveDays: "",
    },
    baseImg: "",
    type: [],
  };

  rules = {
    name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
    useDateValue: [
      {
        validator: this.validatePass,
        required: true,
        trigger: "blur",
      },
    ],
    actRules: [
      { validator: this.rulevalidate, required: true, trigger: "blur" },
    ],
  };

  /** 退出弹窗状态 */
  saveFlag = false;

  /** 优惠券信息 */
  couponContent = {} as any;

  mounted() {
    if (this.$route.params.id) {
      this.getCouponDetail();
    }
  }

  validateday(rule, value, callback) {
    // const regs =  /^[+]{0,1}(\d+)$/;
    if (value > 9) {
      callback(new Error("有效期范围为1-9"));
    } else if (value <= 0) {
      callback(new Error("有效期范围为正整数"));
    } else {
      callback();
    }
  }

  /**
   * 优惠券详情
   */
  getCouponDetail() {
    couponDetail(this.$route.params.id, {}).then((res) => {
      const result = res.data.couponVo;
      const productVos = res.data.discountProductVos;
      this.disType = result.status === 1 ? true : false;
      this.ruleForm.name = result.name;
      this.timeRadio = result.startTime ? "setTime" : "immediate";
      this.ruleForm.useDateValue.effectiveDays = result.effectiveDays;
      if (result.startTime) {
        this.ruleForm.useDateValue.startTime = new Date(result.startTime);
        this.ruleForm.useDateValue.endTime = new Date(result.endTime);
      }
      this.couponContent = { ...result, productVos };
      this.recycleImg = result.recycleImg;
      this.recycleActivity = result.recycleActivity === 1 ? 2 : 1;
    });
  }

  /**
   * 选择时间类型
   */
  chooseTimeType() {
    // 共用一个字段 避免时间格式问题 先清空操作
    this.ruleForm.useDateValue = {
      startTime: "" as any,
      endTime: "" as any,
      effectiveDays: "",
    };
  }

  /**
   * 商品选择类型
   */
  changeModeList(e) {
    console.log(e);
    if (this.disType && e === 2) {
      this.recycleActivity = 1;
      this.$message.error("已发布优惠券不能修改为‘参与回收返券’");
    } else {
      this.recycleActivity = e;
    }
  }

  async uploadProductImg(file) {
    try {
      this.recycleImg = await this.upLoadFile(file);
    } catch (error) {
      console.log(error);
    }
  }

  async upLoadFile(file) {
    try {
      const whiteList = ["image/jpeg", "image/jpg", "image/png", "image/gif"];
      const isLt2M = file.size < 2 * 1024 * 1024;
      if (!whiteList.includes(file.raw.type)) {
        this.$message.error("上传文件只能是 GIF、JPG或PNG 格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        return;
      }
      const res = await upLoad({
        file: file.raw,
      });
      return res.data;
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 保存发布优惠券
   */
  async save() {
    this.formValid();

    const check = this.checkSecond();

    if (!check) {
      return;
    }

    this.apointComp.pointGoodsList.forEach((item) => {
      item.productId = item.id;
    });
    const param = {
      name: this.ruleForm.name,
      effectiveDays:
        this.timeRadio === "immediate"
          ? this.ruleForm.useDateValue.effectiveDays
          : "",
      startTime:
        this.timeRadio === "immediate"
          ? ""
          : new DateUtil("").getYMDs(this.ruleForm.useDateValue.startTime) +
            " 00:00:00",
      endTime:
        this.timeRadio === "immediate"
          ? ""
          : new DateUtil("").getYMDs(this.ruleForm.useDateValue.endTime) +
            " 23:59:59",
      effectiveType: this.timeRadio === "setTime" ? 0 : 1,
      giveType: 0,
      productType: this.apointComp.goodRadio,
      couponProducts: this.apointComp.pointGoodsList,
      id: this.$route.params.id ? (this.couponContent as any).id : "",
      ...this.addComp.couponList[0],
      recycleActivity: this.recycleActivity === 1 ? 0 : 1,
      recycleImg: this.recycleImg,
    };
    await this.getRuleModel();

    if (this.$route.params.id) {
      this.edit(param);
      return;
    }

    if (
      this.recycleActivity === 2 &&
      this.addComp.couponList[0].couponType !== 0
    ) {
      this.$message.error("只有无门槛折扣券参与回收返券功能，请重新编辑");
      return;
    }

    await addCoupon(param)
      .then((res) => {
        console.log(res);
        this.saveFlag = true;
        this.$message.success("发布成功");
        this.$router.push({ name: "CouponIndex" });
      })
      .catch((err) => {
        this.$message.error(err);
      });
  }

  /**
   * 验证表单
   */
  formValid() {
    return this.fromRef.validate();
  }

  async getRuleModel() {
    try {
      await this.addComp.validate();
      return;
    } catch (error) {
      return Promise.reject(error);
    }
  }

  /**
   * 二次验证条件
   */
  checkSecond() {
    if (this.ruleForm.name === "") {
      this.$message.error("请输入优惠券名称");
      return false;
    }

    if (this.timeRadio === "setTime") {
      const start = this.ruleForm.useDateValue.startTime.getTime();
      const end = this.ruleForm.useDateValue.endTime.getTime();
      const now = new Date(new DateUtil("").getYMD(new Date())).getTime();
      if (this.couponContent.status === 1) {
        if (start > end) {
          return false;
        }
      } else {
        if (start > end || start < now) {
          return false;
        }
      }
    } else {
      if (!Number(this.ruleForm.useDateValue.effectiveDays)) {
        this.$message.error("请输入大于0的有效时间");
        return false;
      }
    }

    if (
      this.apointComp.goodRadio !== 0 &&
      this.apointComp.pointGoodsList.length === 0
    ) {
      this.$message.error("请选择指定商品");
      return false;
    }
    return true;
  }

  /**
   * 编辑优惠券
   */
  edit(param) {
    editCoupon(param).then((res) => {
      if (res.code === 200) {
        this.saveFlag = true;
        this.$message.success("编辑成功");
        this.$router.push({ name: "CouponIndex" });
      }
    });
  }

  beforeRouteLeave(to, from, next) {
    if (this.saveFlag) {
      next();
      return;
    }
    this.$confirm(
      `确定要退出${
        this.$route.params.id ? "编辑" : "发布"
      }优惠券活动?退出后，未保存的信息将不会保留!`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(() => {
      this.addComp.clearValidate();
      next();
    });
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin: 10px 0px;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
  margin-left: 10px;
}
.demo-ruleForm {
  margin-left: 15px;
}

.remark {
  margin-left: 20px;
  color: #9b9b9b;
}

/deep/ .el-radio {
  margin-right: 20px;
  margin-left: 15px;
}

.pageButtom {
  margin-top: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

@include b(couponUpload) {
  display: flex;

  @include e(baseUpload) {
    position: relative;
    border: 2px dashed #e6e6e6;
    width: 330px;
    height: 400px;
    border-radius: 10px;
    padding: 10px;
    margin-left: 20px;
    margin-top: 40px;
    display: flex;

    @include m(inUpload) {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      width: 100%;
    }
  }
}

.position1 {
  position: absolute;
  display: flex;
  justify-content: center;
  width: 80%;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  top: 80px;
  left: 34px;
}

.position2 {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80%;
  height: 50px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  bottom: 40px;
  left: 34px;
}

.couponUploadTip {
  display: flex;
  flex-wrap: wrap;
  height: 60px;
  margin-top: 50px;

  &__tip {
    display: flex;
    margin: 80px 0px 0px 40px;
    p {
      color: #2e99f3;
      font-size: 14px;
      margin-right: 30px;
    }
    div {
      color: #cfcfcf;
      font-size: 14px;
    }
  }

  &__tipTwo {
    color: #ff3b4b;
    font-size: 14px;
    margin-left: 40px;
  }
}
</style>
